<!-- 项目信息 -->
<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="项目名称" name="debtorName">
						<a-input
							v-model:value.trim="searchFormState.projectName"
							placeholder="请输入项目名称"
							allowClear
							@pressEnter="onSearch"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="onSearch">查询</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false" class="mt-2">
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator>
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()">
						<template #icon>
							<plus-outlined />
						</template>
						新增
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)">编辑</a>
						<a-divider type="vertical" />
						<a-popconfirm title="确定要删除此项目吗？" @confirm="deleteModule(record)">
							<a-button type="link" danger size="small">删除</a-button>
						</a-popconfirm>
						<a-divider type="vertical" />
						<a @click="handleBalance(record)">余额</a>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<!-- 编辑项目信息 -->
	<Form ref="formRef" @successful="tableRef.refresh(true)" />
	<!-- 余额管理 -->
	<a-drawer v-model:open="balanceOpen" title="余额" placement="right" width="950" @close="closeBalance">
		<div class="balance-drawer">
			<div class="statis">
				<div class="statis-count">
					<div class="statis-count-item">
						<h5>短信可用余额</h5>
						<p>￥{{ curRowInfo.smsAmount.toFixed(2) }}</p>
					</div>
					<span>=</span>
					<div class="statis-count-item">
						<h5>短信总余额</h5>
						<p>￥{{ (curRowInfo.smsAmount + curRowInfo.smsFreezeAmount).toFixed(2) }}</p>
					</div>
					<span>-</span>
					<div class="statis-count-item">
						<h5>短信冻结余额</h5>
						<p>￥{{ curRowInfo.smsFreezeAmount.toFixed(2) }}</p>
					</div>
				</div>
				<a-button class="statis-btn" @click="recharge">充值</a-button>
			</div>
			<a-divider />
			<s-table :columns="balanceColumns" :data="loadBalanceData" bordered ref="balanceTbRef">
				<template #operator>
					<a-range-picker v-model:value="dateRange" valueFormat="YYYY-MM-DD" />
					<span class="m-l-16">
						交易类型：<a-select v-model:value="foundsType" placeholder="请选择类型" :options="FoundsFlowOptions" />
					</span>
					<span class="m-l-16 m-r-16">
						消费方式：<a-select v-model:value="transType" placeholder="请选择类型" :options="TransTypeOptions" />
					</span>

					<a-button type="primary" @click="balanceSearch">查询</a-button>
					<a-button class="m-l-16 m-r-16" @click="resetSearch">重置</a-button>
				</template>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'action'">
						<a-space>
							<a @click="getFoundsDetails(record)">详情</a>
						</a-space>
					</template>
					<template v-if="column.dataIndex === 'foundsPre' || column.dataIndex === 'foundsAvailable'">
						<span>
							{{ Number(record[column.dataIndex]).toFixed(2) }}
						</span>
					</template>
					<template v-if="column.dataIndex === 'foundsAmount'">
						<span
							:style="{
								color: record['transType'] === 0 || Number(record['transType']) == 2 ? '#52c41a' : '#ff4d4f',
								fontWeight: 500
							}"
						>
							{{
								`${
									record['transType'] === 0 || Number(record['transType']) === 2 ? '-' : '+'
								}${Number(record[column.dataIndex]).toFixed(2)}`
							}}
						</span>
					</template>
				</template>
			</s-table>
			<div id="pieCharts"></div>
		</div>
	</a-drawer>
	<!-- 充值弹框 -->
	<a-modal
		v-model:open="rechargeVisible"
		title="充值"
		@ok="handleRecharge"
		@cancel="handleCancel"
		:confirmLoading="confirmLoading"
	>
		<a-form
			:model="rechargeForm"
			class="m-t-24 foundsForm"
			:rules="rechargeFormRules"
			layout="vertical"
			ref="rechargeFormRef"
		>
			<a-form-item>
				<span>当前余额: {{ curRowInfo.smsAmount.toFixed(2) }}</span>
			</a-form-item>
			<a-form-item label="充值金额" name="foundsAmount">
				<a-input-number v-model:value="rechargeForm.foundsAmount" type="number" style="width: 100%" />
			</a-form-item>
			<a-form-item label="交易类型">
				<a-select v-model:value="rechargeForm.foundsType" placeholder="请选择类型" :options="FoundsFlowOptions" />
			</a-form-item>
			<a-form-item label="充值备注">
				<a-textarea
					v-model:value="rechargeForm.foundsRemark"
					placeholder="请输入充值备注信息"
					:auto-size="{ minRows: 2, maxRows: 5 }"
					:maxlength="100"
					show-count
				/>
			</a-form-item>
			<a-form-item label="审批图" name="file">
				<a-upload
					list-type="picture"
					v-model:file-list="uploadFileList"
					@change="uploadChange"
					:beforeUpload="() => false"
				>
					<a-button>
						<upload-outlined></upload-outlined>
						上传
					</a-button>
				</a-upload>
			</a-form-item>
		</a-form>
	</a-modal>
	<!-- 充值流水详情 -->
	<a-modal v-model:open="foundsDetailsVisible" title="充值详情" :footer="null">
		<a-form :model="foundsDetailsForm" class="m-t-24 foundsForm">
			<a-form-item label="项目名称">
				<span>
					{{ foundsDetailsForm.projectName }}
				</span>
			</a-form-item>
			<a-form-item label="充值人">
				<span>{{ foundsDetailsForm.createUserName }}</span>
			</a-form-item>
			<a-form-item label="变动金额">
				<span
					:style="{
						color:
							foundsDetailsForm['transType'] === 0 || Number(foundsDetailsForm['transType']) == 2
								? '#52c41a'
								: '#ff4d4f',
						fontWeight: 500
					}"
				>
					{{
						`${
							foundsDetailsForm['transType'] === 0 || Number(foundsDetailsForm['transType']) == 2 ? '-' : '+'
						}${foundsDetailsForm.foundsAmount.toFixed(2)}`
					}}
				</span>
			</a-form-item>
			<a-form-item label="审批图">
				<img :src="'data:image/png;base64,' + foundsDetailsForm.applyPhoto" alt="" style="width: 100%" />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup name="Company">
	import projectApi from '@/api/tjzy/project/projectApi'
	import foundsApi from '@/api/tjzy/project/foundsApi'
	import Form from '@/views/tjzy/project/form.vue'
	import dayjs from 'dayjs'
	import tool from '@/utils/tool'
	import { nextTick } from 'vue'
	import { message } from 'ant-design-vue'
	import * as echarts from 'echarts'
	//===============================================DATA====================================================
	let pieOptions = ref({
		title: {
			text: '余额分布',
			left: 'center'
		},
		tooltip: {
			trigger: 'item',
			formatter: '{b} : {c} ({d}%)'
		},
		legend: {
			orient: 'horizontal',
			top: '50px'
		},
		series: [
			{
				type: 'pie',
				top: '100px',
				data: []
			}
		]
	})
	let pieChartDom = ref()
	let pieChart = ref()
	const searchFormState = ref({
		projectName: ''
	})
	const tableRef = ref()
	const balanceTbRef = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true }
	//项目信息列
	const columns = [
		{
			title: '所属产品',
			dataIndex: 'productName'
		},
		{
			title: '项目编号',
			dataIndex: 'projectCode'
		},
		{
			title: '项目名称',
			dataIndex: 'projectName'
		},
		{
			title: '项目描述',
			dataIndex: 'projectDescription',
			ellipsis: true
		},
		// {
		// 	title: '电话可用余额',
		// 	dataIndex: 'phoneAmount',
		// 	customRender: ({ text, record, index }) => {
		// 		return Number(record.phoneAmount).toFixed(2)
		// 	}
		// },
		// {
		// 	title: '电话冻结金额',
		// 	dataIndex: 'phoneFreezeAmount',
		// 	customRender: ({ text, record, index }) => {
		// 		return Number(record.phoneFreezeAmount).toFixed(2)
		// 	}
		// },
		{
			title: '短信可用余额',
			dataIndex: 'smsAmount',
			ellipsis: true,
			customRender: ({ text, record, index }) => {
				return Number(record.smsAmount).toFixed(2)
			}
		},
		{
			title: '短信冻结金额',
			dataIndex: 'smsFreezeAmount',
			ellipsis: true,
			customRender: ({ text, record, index }) => {
				return Number(record.smsFreezeAmount).toFixed(2)
			}
		},
		{
			title: '在催案件量',
			dataIndex: 'caseLoad',
			ellipsis: true
		},
		{
			title: '在催人力',
			dataIndex: 'debtUser',
			ellipsis: true
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: '200px',
			scopedSlots: { customRender: 'action' }
		}
	]

	//余额管理列
	const balanceColumns = [
		{
			title: '项目名称',
			dataIndex: 'projectName'
		},
		{
			title: '变动前金额',
			dataIndex: 'foundsPre'
		},
		{
			title: '变动金额',
			dataIndex: 'foundsAmount'
		},
		{
			title: '变动后金额',
			dataIndex: 'foundsAvailable'
		},
		{
			title: '交易类型',
			dataIndex: 'foundsTypeName'
		},
		{
			title: '消费方式',
			dataIndex: 'transTypeName'
		},

		{
			title: '时间',
			dataIndex: 'createTime'
		},
		{
			title: '操作人',
			dataIndex: 'createUserName'
		},
		// {
		// 	title: '备注',
		// 	dataIndex: 'foundsRemark'
		// },
		{
			title: '操作',
			dataIndex: 'action'
		}
	]
	const FoundsFlowOptions = tool.dictList('FoundsFlowType')
	const TransTypeOptions = tool.dictList('TransType')
	const uploadApi = '/api/bizapp/tjzy/founds/uploadFoundsFlow' // 上传地址
	const rechargeFormRef = ref()
	let rechargeVisible = ref(false) //充值弹框显示
	let dateRange = ref([dayjs(new Date()).format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')]) //充值日期范围

	let balanceOpen = ref(false) //余额管理弹框显示
	let curRowInfo = ref({}) //当前行信息
	let foundsType = ref('0') //余额管理类型
	let transType = ref('-1') //交易类型
	let rechargeForm = ref({
		foundsAmount: '', //充值金额
		foundsType: '0', //交易类型
		foundsRemark: '',
		file: null
	})
	let curRowFoundsDetails = ref({}) //当前行充值详情信息
	let uploadFileList = ref([])
	let selectedRowKeys = ref([])
	let foundsDetailsVisible = ref(false) //充值详情显示
	let foundsDetailsForm = ref({})

	//===============================================METHODS====================================================
	// 充值金额校验
	const validateFoundsAmount = async (rule, value, callback) => {
		if (!value) {
			// callback(new Error('请输入充值金额'))
			return Promise.reject(`${value === 0 ? '充值金额必须大于0' : '请输入充值金额'}`)
		} else if (value < 0) {
			return Promise.reject('充值金额必须大于0')
		} else if (value > 10000) {
			// callback(new Error('充值金额不能大于10000'))
			return Promise.reject('充值金额不能大于10000')
		}
		return Promise.resolve()
	}
	//充值图片校验
	const validateImg = async (rule, value, callback) => {
		if (value) {
			const isImage = value.type.startsWith('image/')
			if (!isImage) {
				// callback(new Error('只能上传图片文件!'))
				return Promise.reject('只能上传图片文件!')
			}
			const isLt1M = value.size / 1024 / 1024 < 1
			if (!isLt1M) {
				message.error('图片必须小于 1MB!')
				// callback(new Error('图片必须小于 1MB!'))
				return Promise.reject('图片必须小于 1MB!')
			}
		} else {
			// callback(new Error('请上传充值审批图'))
			return Promise.reject('请上传充值审批图')
		}
		return Promise.resolve()
	}
	let rechargeFormRules = ref({
		foundsAmount: [{ required: true, validator: validateFoundsAmount, trigger: 'blur' }],
		file: [{ required: true, validator: validateImg, trigger: 'change' }]
	})
	let confirmLoading = ref(false) //充值确认加载状态
	// 列表数据
	// 组件卸载时清理URL
	onUnmounted(() => {
		uploadFileList.value.forEach((file) => {
			if (file.url) {
				URL.revokeObjectURL(file.url)
			}
		})
	})

	// 列表选择配置
	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	// 项目信息列表
	const loadData = (parameter) => {
		return projectApi.projectPage(Object.assign(parameter, searchFormState.value)).then((res) => {
			return res
		})
	}

	// 查询
	const onSearch = () => {
		tableRef.value.refresh(true)
	}
	// 删除
	const deleteModule = (record) => {
		let params = { projectIdList: [record.id] }
		projectApi.delProject(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	//余额管理列表
	const loadBalanceData = (parameter) => {
		const data = {
			projectName: curRowInfo.value.projectName,
			projectBeginTime: `${dateRange.value[0]} 00:00:00`,
			projectEndTime: `${dateRange.value[1]} 23:59:59`,
			foundsType: foundsType.value,
			transType: transType.value
		}
		return foundsApi.foundsPage(Object.assign(parameter, data)).then((res) => {
			// console.log('res', res)
			return res
		})
	}
	// 余额管理查询
	const balanceSearch = () => {
		balanceTbRef.value.refresh(false)
		const obj = {
			projectName: curRowInfo.value.projectName,
			projectBeginTime: `${dateRange.value[0]} 00:00:00`,
			projectEndTime: `${dateRange.value[1]} 23:59:59`,
			foundsType: foundsType.value,
			transType: transType.value
		}
		productAmount(obj)
	}
	//余额管理显示
	const handleBalance = (info) => {
		balanceOpen.value = true
		curRowInfo.value = info
		rechargeForm.value.projectCode = info.projectCode
		rechargeForm.value.projectName = info.projectName
		nextTick(() => {
			if (balanceTbRef.value) {
				balanceSearch()
			}
		})
	}

	// 重置
	const resetSearch = () => {
		dateRange.value = [dayjs(new Date()).format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')]
		foundsType.value = '0'
		transType.value = '-1'
		balanceSearch()
	}
	//充值显示
	const recharge = () => {
		rechargeVisible.value = true
		nextTick(() => {
			rechargeFormRef.value?.resetFields()
		})
	}
	// 添加关闭处理函数
	const handleCancel = () => {
		rechargeFormRef.value?.resetFields()
		uploadFileList.value = []
		rechargeForm.value = {
			foundsAmount: 0,
			foundsType: '0',
			foundsRemark: '',
			file: null
		}
	}
	//充值上传
	// 上传状态改变时的回调
	const uploadChange = (info) => {
		// console.log('info', info)

		// const { status, response } = info.file
		// if (status === 'done') {
		// 	message.success(`${info.file.name} 上传成功`)
		// 	rechargeForm.value.file = info.file.originFileObj // 保存文件对象 // 假设这是返回的图片地址
		// } else if (status === 'error') {
		// 	message.error(`${info.file.name} 上传失败`)
		// }
		// console.log('info', info)
		const file = info.file
		if (file) {
			// 创建本地预览URL
			file.url = URL.createObjectURL(file)
			rechargeForm.value.file = file
			uploadFileList.value = [file]
		}
	}
	const closeBalance = () => {
		dateRange = ref([dayjs(new Date()).format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')]) //充值日期范围
		foundsType.value = '0'
		transType.value = '-1'
	}
	//===============================================REQUEST====================================================
	//充值确认处理
	const handleRecharge = () => {
		rechargeFormRef.value
			.validate()
			.then(() => {
				confirmLoading.value = true
				const formData = new FormData()
				const jsonData = {
					projectCode: curRowInfo.value.projectCode,
					projectName: curRowInfo.value.projectName,
					foundsAmount: rechargeForm.value.foundsAmount, // 注意这里使用 rechargeAmount
					foundsType: rechargeForm.value.foundsType,
					foundsRemark: rechargeForm.value.foundsRemark
				}
				// console.log('jsonData', jsonData)
				formData.append('founds', new Blob([JSON.stringify(jsonData)], { type: 'application/json' }))

				if (rechargeForm.value.file) {
					formData.append('file', rechargeForm.value.file)
				}

				foundsApi.foundsUpload(formData).then((res) => {
					confirmLoading.value = false
					message.success('充值成功')
					balanceSearch()
					uploadFileList.value = []
					rechargeForm.value = {
						foundsAmount: 0,
						foundsType: '0',
						foundsRemark: '',
						file: null
					}
					rechargeVisible.value = false
				})
			})
			.catch((error) => {
				message.error('表单校验失败，请重新核对表单信息')
			})
	}

	//获取充值详情
	const getFoundsDetails = (record) => {
		// console.log('receipt', receipt)
		foundsApi.detailFoundsFlow({ id: record.id }).then((res) => {
			foundsDetailsForm.value = res
			console.log('refoundsDetailsForms', foundsDetailsForm.value)
		})
		foundsDetailsVisible.value = true
	}
	//短信金额统计
	const productAmount = (data) => {
		let seriesData = []
		foundsApi.productAmount(data).then((res) => {
			if (res.length === 0) {
				seriesData = [{ value: 0, name: '暂无数据' }]
				pieOptions.value.color = ['#eee']
			} else {
				pieOptions.value.color = ['#5A6FC0', '#9ECA7F', '#F2CA6B', '#EE7975']
				res.forEach((item) => {
					const i = seriesData.findIndex((i) => i.name === item.transType)
					if (i !== -1) {
						seriesData[i].value += item.foundsAmount
					} else {
						seriesData.push({
							value: item.foundsAmount,
							name: item.transType
						})
					}
				})
				seriesData.forEach((item) => {
					item.name = TransTypeOptions.find((i) => i.value == item.name)?.label
				})
			}
			//绘制饼图
			pieOptions.value.series[0].data = seriesData
			pieChartDom.value = document.getElementById('pieCharts')
			pieChart.value = echarts.init(pieChartDom.value)
			pieChart.value.setOption(pieOptions.value)
		})
	}
</script>
<style scoped lang="less">
	.statis {
		display: flex;
		justify-content: space-between;
		align-items: end;

		.statis-count {
			width: 35%;
			display: flex;
			justify-content: space-between;
			align-items: end;

			.statis-count-item {
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				h5 {
					color: #00000073;
				}

				p {
					margin-bottom: 0;
				}
			}

			.statis-count-item:nth-child(1) {
				p {
					color: #ed5c38;
					font-weight: 700;
				}
			}
		}
	}
	.balance-drawer {
		display: flex;
		flex-direction: column;
		:deep(.table-wrapper) {
			flex: 1;
		}
		#pieCharts {
			margin-top: 20px;
			width: 950px;
			height: 350px;
		}
	}
</style>
